package main.java.com.chegg.coursepicker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.FileUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;



public class IndeedSearch {

	@SuppressWarnings("rawtypes")
	public  TreeMap searchIndeed(int newCourseid, int userid  ){
		//public static void main(String args[] ){
		// int newCourseid = 9;			
		// int userid =1;
		 String url = "http://api.indeed.com/ads/apisearch?publisher=3487170475522198&q=";
         final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
         final String DB_URL = "jdbc:mysql://live-dbpm.dev1.cloud.cheggnet.com/integration";
        //  Database credentials
         final String USER = "tbflix";
         final String PASS = "c4tny2003";
          TreeMap searchMap = new TreeMap( );
          File file = null;
          file = new File("C://opt//docs//source//temp/");         
	        String[] myFiles;       
	            if(file.isDirectory()){   
	                myFiles = file.list();   
	                for (int j=0; j<myFiles.length; j++) {   
	                    File myFile = new File(file, myFiles[j]);    
	                    myFile.delete();   
	                }   
	             }  

        try {
        	Connection conn = null;
        	Statement stmt1 = null;
        	Statement stmt2 = null;
        	//STEP 2: Register JDBC driver
            Class.forName("com.mysql.jdbc.Driver");

            //STEP 3: Open a connection
            System.out.println("Connecting to database...");
            conn = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);

            //STEP 4: Execute a query
            System.out.println("Creating statement...");
            stmt1 = (Statement) conn.createStatement();
            String sql1;
            sql1 = "select course_id from cg_user_course where user_number = "+userid+";";
            ResultSet rs1 = stmt1.executeQuery(sql1);
            ResultSet rs2 = null;
            while(rs1.next()){
           
                String sql2;
	            sql2 = "select keyword from cg_course_detail where hard_qualifier = 'Y' and course_id in ("+newCourseid+","+rs1.getString("course_id")+");";
	            stmt2 = (Statement) conn.createStatement();
	            rs2 = stmt2.executeQuery(sql2);
	            StringBuffer sbf = new StringBuffer();
	                       
	            while(rs2.next()){
	                
	               String keyword = rs2.getString("keyword");
	               sbf.append(keyword + "+");
	             
	            }
	            sbf.deleteCharAt(sbf.length()-1);
	            String keywordsearch = sbf.toString();
	            keywordsearch=keywordsearch.replaceAll(" ", "+");
	            
	           String finalurl = url+keywordsearch+"&format=json&sort=&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2";
	          //  url = "http://api.indeed.com/ads/apisearch?publisher=3487170475522198&q=3D+graphics&format=json&sort=&radius=&st=&jt=&start=&limit=&fromage=&filter=&latlong=1&co=us&chnl=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2";
	
	            System.out.println("url " + finalurl);
	            HttpClient client = new HttpClient();
	            GetMethod method = new GetMethod(finalurl);
	
	            int statusCode = client.executeMethod(method);
	            String str = null;
	            if (statusCode != -1) {
	             str  = method.getResponseBodyAsString();
	            }
	            
	            System.out.println(str);
	            JSONObject json = (JSONObject)new JSONParser().parse(str);
	            JSONArray jarr = (JSONArray) json.get("results");
	            JobDescTO jobTO =  null;
	        
    	            
	           if(jarr!=null){
	        	   for(int i=0;i<jarr.size();i++){
	           
	            	System.out.println(" i = " + i);
	            	JSONObject jto = (JSONObject) jarr.get(i);
	            	jobTO = new JobDescTO();
	            	jobTO.setCity(jto.get("city").toString());
	            	jobTO.setCompany( jto.get("company").toString());
	            	jobTO.setCountry( jto.get("country").toString()) ;
	            	jobTO.setDate( jto.get("date").toString()) ;
	            	jobTO.setExpired( jto.get("expired").toString()) ;
	            	jobTO.setFormattedLocation( jto.get("formattedLocation").toString()) ;
	            	jobTO.setFormattedLocationFull( jto.get("formattedLocationFull").toString()) ;
	            	jobTO.setFormattedRelativeTime( jto.get("formattedRelativeTime").toString()) ;
	            	jobTO.setJobtitle( jto.get("jobtitle").toString()) ;
	            	jobTO.setSnippet( jto.get("snippet").toString()) ;
	            	jobTO.setSource( jto.get("source").toString()) ;
	            	jobTO.setSponsored( jto.get("sponsored").toString()) ;
	            	jobTO.setState( jto.get("state").toString()) ;
	            	jobTO.setUrl(  jto.get("url").toString()) ;
	            	searchMap.put(jto.get("jobkey").toString(),jobTO);
	            	 /***
		             * this part is to create the source files
		             * 
		             */
	               
	            	file = new File("C://opt//docs//source//temp/"+jto.get("jobkey")+".txt");
	            	file.createNewFile();
	            	FileWriter fstream = new FileWriter(file, true); //true tells to append data.
	                BufferedWriter out = new BufferedWriter(fstream);
	                out.write(jto.get("snippet").toString());
	                out.close();
	            	
	            }
	            
	           
	           }
	          
            }
            
            rs2.close();
            stmt2.close();
            rs1.close();
            stmt1.close();
            conn.close();
	          
            
            /***
             * this part is to create the repository files
             * 
             */
            File source = new File("C://opt//docs//source//COURSE_"+newCourseid+".txt");
            File desc = new File("C://opt//docs//source//temp//COURSE_"+newCourseid+".txt");

            FileUtils.copyFile(source, desc);


            AddingFilesToRepository adf = new AddingFilesToRepository();
            adf.addFilesToRepository();
            
            /***
             * this part is to Find similarity 
             * 
             */
            
            PerformingOperationOnCorpus pcs = new PerformingOperationOnCorpus();
            TreeMap similarity = pcs.findSimilarity();
            
            /**
             * populate similarities
             */
            Set keys = searchMap.keySet();
            for (Iterator i = keys.iterator(); i.hasNext();) {
              String key = (String) i.next();
              JobDescTO value = (JobDescTO) searchMap.get(key);
              if(similarity.get(key)!=null){
	              String similarity_percent = similarity.get(key).toString();
	              System.out.println("key " + key + " similarity_percent " + similarity_percent);
	              value.setSimilarity(similarity_percent);
              }
           }
            
             System.out.println("search size " + searchMap.size());
               
             }catch(SQLException se){
                //Handle errors for JDBC
                se.printStackTrace();
             }catch(Exception e){
                //Handle errors for Class.forName
                e.printStackTrace();
             }
        
		return searchMap;
	}
}
              	

    








